package com.zzs.judge.config;

import com.github.dockerjava.api.DockerClient;
import com.zzs.judge.constants.DockerConsts;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.ArrayBlockingQueue;

/**
 * @author zzs
 * @date 2025/03/28
 */
@Component
public class JavaContainerPool {
    @Getter
    @Value("${docker.java.container-size}")
    private int containerSize;

    @Autowired
    private CreateJavaContainer createJavaContainer;

    @Autowired
    private DockerClient dockerClient;
    /**
     * 存放容器id的阻塞队列
     */
    private ArrayBlockingQueue<String> containerIdQueue;

    /**
     * 创建容器池, 把容器id存入containerIdQueue
     */
    @PostConstruct
    private void initContainerPool() {
        containerIdQueue = new ArrayBlockingQueue<>(containerSize);
        for (int i = 0; i < containerSize; i++) {
            String containerId = createJavaContainer.createContainer(DockerConsts.JAVA_CONTAINER_NAME_PREFIX + i);
            containerIdQueue.add(containerId);
        }
    }

    @PreDestroy
    private void destroyContainerPool() {
        System.out.println("---销毁容器池开始---");
        for (String containerId : containerIdQueue) {
            dockerClient.stopContainerCmd(containerId).exec();
            dockerClient.removeContainerCmd(containerId).exec();
            System.out.println("销毁" + containerId + "容器成功");
        }
        System.out.println("---销毁容器池结束---");
    }

    public String getContainerId() throws InterruptedException {
        return containerIdQueue.take();
    }

    public void releaseContainerId(String containerId) {
        containerIdQueue.add(containerId);
    }

}
